package com.stone.zk.lock.api.controller.v1;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * Curator客户端分布式锁测试类
 *
 * @author Mr_wenpan@163.com 2021/08/02 11:34
 */
@Slf4j
@RestController("zkLockTestController.v1")
@RequestMapping("/v1/{organizationId}/zk-curator-lock-test")
public class ZkCuratorLockTestController {

    @Autowired
    private CuratorFramework curatorFramework;

    @GetMapping("curatorLock")
    @ApiOperation(value = "zk-Curator分布式锁测试")
    public String curatorLock() {
        log.debug("curatorLock()方法；");
        //创建锁对象
        InterProcessMutex lock = new InterProcessMutex(curatorFramework, "/order");
        try {
            //获取锁
            if (lock.acquire(30, TimeUnit.SECONDS)) {
                log.debug("获取到锁，开始执行业务逻辑......");
                Thread.sleep(20 * 1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                lock.release();
            } catch (Exception e) {
                log.error("释放锁出现异常，异常信息: ", e);
            }
        }

        return "方法执行完成";
    }

}